<template>
    <div class="app-container">
        <steps :active-step="0" />
        <el-col :span="12">
            <el-form
                :model="form"
                ref="formRef"
                :rules="formRules"
                label-width="80px"
                :inline="false"
                size="normal"
            >
                <el-form-item label="课程标题" prop="title">
                    <el-input v-model="form.title"></el-input>
                </el-form-item>
                <el-form-item label="总课时" prop="lessonNum">
                    <el-input-number v-model="form.lessonNum"></el-input-number>
                </el-form-item>
                <el-form-item :min="0" label="课程价格" prop="price">
                    <el-input-number
                        :min="0"
                        :precision="2"
                        :step="0.01"
                        controls-position="right"
                        v-model="form.price"
                    ></el-input-number>
                </el-form-item>
                <el-form-item label="课程简介" prop="description">
                    <el-input
                        type="textarea"
                        row="3"
                        v-model="form.description"
                    ></el-input>
                </el-form-item>
                <el-form-item label="课程封面" prop="cover">
                    <el-upload
                        class="avatar-uploader"
                        :action="BASE_API + '/eduoss/fileoss'"
                        :show-file-list="false"
                        :on-success="handleAvatarSuccess"
                        :before-upload="beforeAvatarUpload"
                        :on-remove="handleRemove"
                    >
                        <img v-if="imageUrl" :src="imageUrl" class="avatar" />
                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>
                    </el-upload>
                </el-form-item>
                <el-form-item label="课程讲师" prop="teacherId">
                    <el-select
                        v-model="form.teacherId"
                        placeholder="请选择课程讲师"
                        clearable
                    >
                        <el-option
                            v-for="item in teacherList"
                            :key="item.id"
                            :label="item.name"
                            :value="item.id"
                        >
                        </el-option>
                    </el-select>
                </el-form-item>
                <el-form-item label="课程分类" prop="subjectId">
                    <el-cascader
                        v-model="subjectValue"
                        :options="KCFLOptions"
                        :props="defaultProps"
                        @change="getCheckedNodes"
                    >
                    </el-cascader>
                </el-form-item>
                <el-form-item>
                    <el-button type="primary" @click="handleNext"
                        >保存并下一步</el-button
                    >
                </el-form-item>
            </el-form>
        </el-col>
    </div>
</template>

<script>
import Steps from "./components/steps";
import courseApi from "@/api/course";
import teacherApi from "@/api/teacher";
import subjectApi from "@/api/subject";
import { listToTreeList } from "@/utils/index";
export default {
    components: {
        Steps,
    },
    data() {
        return {
            subjectValue:[],
            defaultProps: {
                children: "children",
                label: "title",
                value: 'id',
            },
            KCFLOptions: [],
            teacherList: [],
            imageUrl: "",
            BASE_API: process.env.BASE_API,
            form: {
                cover: null, //课程封面图片路径
                description: null, //课程简介
                id: null, //课程ID
                lessonNum: null, //总课时
                price: 0, //课程销售价格，设置为0则可免费观看
                subjectId: null, //课程专业ID
                subjectParentId: null, //课程一级分类id
                teacherId: null, //课程讲师ID
                title: null, //课程标题
            },
            formRules: {
                title: [
                    {
                        required: true,
                        message: "课程标题不能为空",
                        trigger: "blur",
                    },
                ],
            },
        };
    },
    created() {
        if (this.$route.query.courseId) {
            this.form.id = this.$route.query.courseId;
            this.getCourseInfo();
        }
        this.getTeacherList();
        this.getsubjectList();
    },
    methods: {
      getCheckedNodes(data){
        this.form.subjectParentId = this.subjectValue[0];
        this.form.subjectId = this.subjectValue[1];
      },
        // 获取课程分类 数据列表并转化为树形结构
        async getsubjectList() {
            let res = await subjectApi.getAllSubject();
            if (res.success) {
                let tempList = res.data.list;
                this.KCFLOptions = listToTreeList(tempList);
                console.log(this.KCFLOptions);
            }
        },
        async getTeacherList() {
            let res = await teacherApi.findAll();
            if (res.success) {
                this.teacherList = res.data.items;
            }
        },
        async getCourseInfo() {
            let res = await courseApi.getCourseInfo(this.form.id);
            if (res.success) {
                this.form = res.data.courseInfo;
                this.imageUrl = this.form.cover;
                this.subjectValue[0] = this.form.subjectParentId;
                this.subjectValue[1] = this.form.subjectId;
            } else {
                return this.$message.error(res.msg);
            }
        },
        handleNext() {
            this.$refs.formRef.validate((v) => {
                if (v) {
                    if(this.form.id){
                      this.handleEdit();
                    }else{
                      this.handleAdd();
                    }
                }
            });
        },
        // 添加课程信息
        async handleAdd() {
            let res = await courseApi.addCourseInfo(this.form);
            if (res.success) {
                this.$message.success("添加课程信息成功");
                    this.$router.push({
                        path: "/course/chapter",
                        query: {
                            courseId: res.data.courseId,
                        },
                    });
            } else {
                return this.$message.error(res.msg);
            }
        },
        // 编辑课程信息
        async handleEdit() {
          let res = await courseApi.updateCourseInfo(this.form);
          if (res.success) {
                this.$message.success("更新课程信息成功");
                    this.$router.push({
                        path: "/course/chapter",
                        query: {
                            courseId: res.data.courseId,
                        },
                    });
            } else {
                return this.$message.error(res.msg);
            }
        },

        // 头像上传成功后
        handleAvatarSuccess(res, file) {
            if (res.success) {
                this.imageUrl = res.data.url;
                this.form.cover = this.imageUrl;
            }
        },
        // 头像上传成功前
        beforeAvatarUpload(file) {
            const isLt1M = file.size / 1024 / 1024 < 1;
            if (!isLt1M) {
                this.$message.error("上传头像图片大小不能超过 1MB!");
            }
            return isLt1M;
        },
        handleRemove(file, fileList) {
            console.log(file);
            console.log(fileList);
        },
    },
};
</script>

<style lang="scss" scoped>
::v-deep.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}
.avatar-uploader .el-upload:hover {
    border-color: #409eff;
}
.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 178px;
    height: 178px;
    line-height: 178px;
    text-align: center;
}
.avatar {
    width: 178px;
    height: 178px;
    display: block;
}
</style>